import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);
//定义属性
var stateAll = {
    count:6,
    country:'中国'
};

//定义getters
var getters = {
    count(state){
        return state.count
    },
    isEvebOrOdd(state){
        return state.count%2 ==0?'偶数':'基数';
    }
}

//定义mutation,处理状态（数据）的改变
var mutations = {
    increment(state,payload){
        state.count = state.count + payload.data;
    },
    incrementAsync(state,payload){
        //异步操作
        var p = new Promise((resolve,reject) =>{
            setTimeout(() =>{
                resolve();
            },3000)
        });
        p.then(()=>{
            state.count = state.count + payload.data;
        }).catch(() =>{
            console.log('异步操作');
        })
    }
}

var actions = {
    // increment(context,payload){
    //     debugger
    //     context.commit("increment",payload)
    // }
    increment({commit},payload){
        commit("increment",payload)
    },
    incrementAsync({commit,state},payload){
        //异步操作
        var p = new Promise((resolve,reject) =>{
            setTimeout(() =>{
                resolve();
            },3000)
        });
        p.then(()=>{
            commit("increment",payload);
        }).catch(() =>{
            console.log('异步操作');
        })
    }
}

//创建store对象
var store = new Vuex.Store({
    state:stateAll,
    getters:getters, //getters
    mutations:mutations, //mutations
    actions:actions //actions
})

//到处store对象
export default store;